const database = require('../database')

//为文章分配一个id
const atrributeId = () => {
    //丢个promise出去，免得又收不到返回值
    return new Promise((resolve, reject) => {
        const sql = 'select * from blogs'
        database.query(sql, (error, result) => {
            if(error) {
                reject(error)
            } else if(result.length == 0) {
               resolve(1)
            } else {
                let idArray = []
                for(let i = 0; i < result.length; i++) {
                    idArray.push(result[i].id)
                }
                for(let i = 1; i <= result.length; i++) {
                    if(idArray.includes(i) == false) {
                       resolve(i)
                    }
                }
                resolve(result.length+1)
            }
        })
    }).catch(err => {
        console.log('分配Id算法又炸了!!!')
    })
}

module.exports = atrributeId